import csv,os,re
from PIL import Image

# CSV清洗
def replace_between_chars(text, start_char, end_char, replacement="@"):
    """
    将字符串中从 start_char 到 end_char 之间的内容替换为 replacement。
    """
    pattern = re.escape(start_char) + r'.*?' + re.escape(end_char)
    return re.sub(pattern, start_char + replacement + end_char, text)
def remove_after_second_occurrence(text, target_char):
    # 找到第一次出现的位置
    first_index = text.find(target_char)
    if first_index == -1:
        return text  # 如果目标字符不存在，直接返回原字符串
    
    # 找到第二次出现的位置（从第一次之后开始搜索）
    second_index = text.find(target_char, first_index + 1)
    if second_index == -1:
        return text  # 如果没有第二次出现，直接返回原字符串
    
    # 截取字符串，保留第二次出现之前的部分
    return text[:second_index]
def remove_before_first_occurrence(text, target_char):
    index = text.find(target_char)
    if index == -1:
        return text  # 如果目标字符不存在，直接返回原字符串
    return text[index:]

def remove_after_first_occurrence(text, target_char):
    index = text.find(target_char)
    if index == -1:
        return text  # 如果目标字符不存在，直接返回原字符串
    return text[:index + 1]  # 保留目标字符及其之前的内容

def read_csv_file(file_path):
    arr=[]
    i=0
    with open(file_path, mode='r', encoding='utf-8') as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if i>0:
                file=os.path.basename(row[0])
                arr.append({file:row[1]})
            i+=1
    return arr

def resize_image_by_cm(input_path, output_path, width_cm=None, height_cm=None, dpi=300):
    """
    根据指定的宽度或高度（以厘米为单位）等比例调整 PNG 图片的大小，并设置分辨率为 300 DPI。
    
    :param input_path: 输入图片路径
    :param output_path: 输出图片路径
    :param width_cm: 指定的宽度（厘米），如果为 None 则根据高度调整
    :param height_cm: 指定的高度（厘米），如果为 None 则根据宽度调整
    :param dpi: 分辨率（默认 300 DPI）
    """
    # 打开原始图片
    img = Image.open(input_path)
    original_width, original_height = img.size

    # 将厘米转换为像素
    if width_cm is not None:
        target_width = int(width_cm * dpi / 2.54)
        # 根据宽高比计算高度
        target_height = int(target_width * original_height / original_width)
    elif height_cm is not None:
        target_height = int(height_cm * dpi / 2.54)
        # 根据宽高比计算宽度
        target_width = int(target_height * original_width / original_height)
    else:
        raise ValueError("必须指定宽度或高度之一")
    # 调整图片大小
    resized_img = img.resize((target_width, target_height), Image.Resampling.LANCZOS)

    # 设置 DPI
    resized_img.info['dpi'] = (dpi, dpi)

    # 保存调整后的图片
    resized_img.save(output_path, format="PNG", dpi=(dpi, dpi))
    print(f"图片已调整大小并保存到 {output_path}")
    
csv_path='output.csv'
datas=read_csv_file(csv_path)
print(len(datas))
fail_tag=0
data_result=[]
for data in datas:
    for key,value in data.items():
        value=replace_between_chars(value,'(',')')
        value=replace_between_chars(value,'米',':')        
        value=replace_between_chars(value,'厘',':')
        value=remove_after_second_occurrence(value,'米')
        value=remove_before_first_occurrence(value,':')
        value=remove_after_first_occurrence(value,'米')
        numbers = re.findall(r'\d+\.?\d*', value)
        result = [float(num) if '.' in num else int(num) for num in numbers]
        result = [x for x in result if x != 100]
        if(len(result)==3):
            result.pop(1)
        if(len(result)!=2):
            fail_tag=fail_tag+1
        else:
            data_result.append({key:result})
            # print('width',result[0],'height',result[1],key)
print(len(data_result))
print(fail_tag)


num=0
for data in data_result:
    for key,value in data.items():
        tag=''
        v=0
        if 6<value[1]<50:
            v=value[1]
            tag='height'
        if 6<value[0]<50:
            v=value[0]
            tag='width'
        if v!=0:
            # print(key,v,tag)
            input_path="D:/Desk/0312-炳哥尺寸转换/B#分割/pattern/"+key
            output_path="D:/Desk/0312-炳哥尺寸转换/C#结果/success/"+key
            if tag=='height':
                resize_image_by_cm(input_path, output_path, width_cm=None, height_cm=v, dpi=300)
            if tag=='width':
                resize_image_by_cm(input_path, output_path, width_cm=v, height_cm=None, dpi=300)
            num=num+1
            print('现在调整：',num)
            

        